<template>
  <div class="operation-logs">
    <el-card>
      <div slot="header">
        <span>操作日志</span>
      </div>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索操作人或操作内容"
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch"
              clearable
            />
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.level" placeholder="选择级别" clearable>
              <el-option label="信息" value="info" />
              <el-option label="警告" value="warn" />
              <el-option label="错误" value="error" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 日志列表 -->
      <el-table
        :data="logList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column prop="operation" label="操作内容" width="200" show-overflow-tooltip />
        <el-table-column prop="module" label="模块" width="120" />
        <el-table-column prop="level" label="级别" width="100">
          <template slot-scope="scope">
            <el-tag :type="getLevelType(scope.row.level)" size="small">
              {{ getLevelName(scope.row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" width="130" />
        <el-table-column prop="userAgent" label="用户代理" width="200" show-overflow-tooltip />
        <el-table-column prop="requestData" label="请求数据" width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="showRequestData(scope.row)">
              查看请求
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="responseData" label="响应数据" width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="showResponseData(scope.row)">
              查看响应
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="操作时间" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleView(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      title="日志详情"
      :visible.sync="detailDialogVisible"
      width="800px"
    >
      <div v-if="currentLog" class="log-detail">
        <div class="detail-item">
          <label>操作人:</label>
          <p>{{ currentLog.operator }}</p>
        </div>
        <div class="detail-item">
          <label>操作内容:</label>
          <p>{{ currentLog.operation }}</p>
        </div>
        <div class="detail-item">
          <label>模块:</label>
          <p>{{ currentLog.module }}</p>
        </div>
        <div class="detail-item">
          <label>级别:</label>
          <p>
            <el-tag :type="getLevelType(currentLog.level)" size="small">
              {{ getLevelName(currentLog.level) }}
            </el-tag>
          </p>
        </div>
        <div class="detail-item">
          <label>IP地址:</label>
          <p>{{ currentLog.ip }}</p>
        </div>
        <div class="detail-item">
          <label>用户代理:</label>
          <p>{{ currentLog.userAgent }}</p>
        </div>
        <div class="detail-item">
          <label>操作时间:</label>
          <p>{{ formatDate(currentLog.createdAt) }}</p>
        </div>
        <div class="detail-item">
          <label>请求数据:</label>
          <div class="request-data">
            <pre>{{ formatJson(currentLog.requestData) }}</pre>
          </div>
        </div>
        <div class="detail-item">
          <label>响应数据:</label>
          <div class="response-data">
            <pre>{{ formatJson(currentLog.responseData) }}</pre>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 请求数据对话框 -->
    <el-dialog
      title="请求数据"
      :visible.sync="requestDataDialogVisible"
      width="600px"
    >
      <div class="request-data">
        <pre>{{ formatJson(currentRequestData) }}</pre>
      </div>
    </el-dialog>

    <!-- 响应数据对话框 -->
    <el-dialog
      title="响应数据"
      :visible.sync="responseDataDialogVisible"
      width="600px"
    >
      <div class="response-data">
        <pre>{{ formatJson(currentResponseData) }}</pre>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "OperationLogs",
  data() {
    return {
      loading: false,
      logList: [],
      searchForm: {
        keyword: "",
        level: "",
        dateRange: []
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      detailDialogVisible: false,
      requestDataDialogVisible: false,
      responseDataDialogVisible: false,
      currentLog: null,
      currentRequestData: null,
      currentResponseData: null
    }
  },
  async created() {
    await this.loadLogList()
  },
  methods: {
    async loadLogList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
        
        // 处理日期范围
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startTime = this.searchForm.dateRange[0]
          params.endTime = this.searchForm.dateRange[1]
        }
        delete params.dateRange
        
        const response = await this.$http.get("/admin/logs", { params })
        if (response.data.code === 200) {
          this.logList = response.data.data.list
          this.pagination.total = response.data.data.total
        }
      } catch (error) {
        console.error("加载日志列表失败:", error)
        // 使用模拟数据
        this.loadMockData()
      } finally {
        this.loading = false
      }
    },

    loadMockData() {
      this.logList = [
        {
          id: 1,
          operator: "admin",
          operation: "登录系统",
          module: "用户管理",
          level: "info",
          ip: "192.168.1.100",
          userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
          requestData: { username: "admin", password: "******" },
          responseData: { code: 200, message: "登录成功" },
          createdAt: "2025-09-20T10:30:00"
        },
        {
          id: 2,
          operator: "admin",
          operation: "添加学生",
          module: "学生管理",
          level: "info",
          ip: "192.168.1.100",
          userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
          requestData: { name: "张三", phone: "18612341234" },
          responseData: { code: 200, message: "添加成功" },
          createdAt: "2025-09-20T10:35:00"
        },
        {
          id: 3,
          operator: "admin",
          operation: "删除任务",
          module: "任务管理",
          level: "warn",
          ip: "192.168.1.100",
          userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
          requestData: { taskId: 123 },
          responseData: { code: 200, message: "删除成功" },
          createdAt: "2025-09-20T10:40:00"
        }
      ]
      this.pagination.total = 3
    },

    handleSearch() {
      this.pagination.currentPage = 1
      this.loadLogList()
    },

    handleReset() {
      this.searchForm = {
        keyword: "",
        level: "",
        dateRange: []
      }
      this.pagination.currentPage = 1
      this.loadLogList()
    },

    handleView(row) {
      this.currentLog = row
      this.detailDialogVisible = true
    },

    showRequestData(row) {
      this.currentRequestData = row.requestData
      this.requestDataDialogVisible = true
    },

    showResponseData(row) {
      this.currentResponseData = row.responseData
      this.responseDataDialogVisible = true
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.loadLogList()
    },

    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadLogList()
    },

    getLevelType(level) {
      const levelMap = {
        info: "info",
        warn: "warning",
        error: "danger"
      }
      return levelMap[level] || "info"
    },

    getLevelName(level) {
      const levelMap = {
        info: "信息",
        warn: "警告",
        error: "错误"
      }
      return levelMap[level] || "未知"
    },

    formatDate(date) {
      if (!date) return '未知'
      return new Date(date).toLocaleString('zh-CN')
    },

    formatJson(data) {
      if (!data) return '无数据'
      try {
        return JSON.stringify(data, null, 2)
      } catch (error) {
        return String(data)
      }
    }
  }
}
</script>

<style scoped>
.operation-logs {
  padding: 0;
}

.search-area {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.log-detail {
  padding: 20px 0;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
}

.detail-item p {
  margin: 5px 0;
  line-height: 1.6;
}

.request-data,
.response-data {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  font-size: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.request-data pre,
.response-data pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
